package br.com.consultsystems.interfaces.service.configuracao;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;

import org.jboss.resteasy.logging.Logger;

import br.com.consultsystems.dominio.configuracao.Usuario;
import br.com.consultsystems.interfaces.Resposta;
import br.com.consultsystems.libutils.exception.CredenciaisInvalidasException;
import br.com.consultsystems.negocio.spec.configuracao.UsuarioNegocio;

import com.google.gson.Gson;

@Path("service/login")
public class LoginService {

	private static final Logger LOG = Logger.getLogger(LoginService.class);

	@Inject
	UsuarioNegocio usuarioNegocio;
	
	@Context
	HttpServletRequest httpServletRequest;

	@POST
	@Path("/acessar")
	@Produces(MediaType.APPLICATION_JSON)
	public String acessar(String json) {
		
		Gson gson = new Gson();
		Resposta resposta = new Resposta();

		Usuario usuario = gson.fromJson(json, Usuario.class);
		
		try {
			usuario = usuarioNegocio.login(usuario.getEmail(), usuario.getSenha());
			if(usuario != null) {
	
				resposta.setStatus(true);
				resposta.setMessage("Credenciais válidas");
	
				/*
				JBOSS 7.1 the .undefined part is due to the instance-id not being configured in the standalone.xml file.
				The following addition to the standalone.xml file would replace the .undefined with a configured text: 
				<subsystem xmlns="urn:jboss:domain:web:1.1" default-virtual-server="default-host" native="false"instance-id="hostA">
				*/
				HttpSession httpSession = httpServletRequest.getSession(true);
				usuario.setSession(httpSession.getId().replaceAll(".undefined", ""));
				StringBuffer sb = new StringBuffer(usuario.getSession());
				/* Inverte e contena o temanho */
				LOG.info("Acessar Key: " + (sb.reverse().toString()+sb.length()));
				httpSession.setAttribute(sb.reverse().toString()+sb.length(), usuario);
				httpSession.putValue(sb.reverse().toString()+sb.length(), usuario);
				resposta.setObject(usuario);
			} else {
				LOG.info("Credenciais inválidas");
				resposta.setStatus(false);
				resposta.setMessage("Credenciais inválidas");
				resposta.setObject(null);
			}
		} catch (CredenciaisInvalidasException e) {
			LOG.error("Credenciais Inválidas", e);
			resposta.setStatus(false);
			resposta.setMessage("Credenciais inválidas");
			resposta.setObject(null);
		} catch (Exception e) {
			LOG.error("Problemas de comunicação: ", e);
			resposta.setStatus(false);
			resposta.setMessage("Credenciais inválidas");
			resposta.setObject(null);
		}
		
		LOG.info("Acessar -> Respota JSON: " + gson.toJson(resposta));
		return gson.toJson(resposta);
	}

	@POST
	@Path("/validar")
	@Produces(MediaType.APPLICATION_JSON)
	public String validar(String usersessionid) {

		Gson gson = new Gson();
		Resposta resposta = new Resposta();
		resposta.setStatus(false);
		
		/* Recupear a SessÃ£o se criar nova */
		HttpSession httpSession = httpServletRequest.getSession(false);
		LOG.info("Session: " + (httpSession != null));
		
		if(httpSession != null) {
			/* Inverte e contena o temanho */
			StringBuffer sb = new StringBuffer(usersessionid);
			String key = sb.reverse().toString() + sb.length();
			/* Busca pelo usuário */
			LOG.info("Id:" + httpSession.getId() + "; Validar Key: " + (sb.reverse().toString()+sb.length()));
			Usuario usuario = (Usuario)httpSession.getValue(key);
			resposta.setStatus(usuario != null);
		}
		
		return gson.toJson(resposta);
	}
	
	@POST
	@Path("/sair")
	@Produces(MediaType.APPLICATION_JSON)
	public String sair(String key) {
		
		Gson gson = new Gson();
		Resposta resposta = new Resposta();

		/* Recupear a SessÃ£o se criar nova */
		HttpSession httpSession = httpServletRequest.getSession(false);
		LOG.info("Session: " + httpSession.getId() + " Invalidate");
		httpSession.invalidate();
		
		resposta.setStatus(true);
		return gson.toJson(resposta);
		
	}
	
}
